package org.nf.web.servlet.view;

import org.nf.web.servlet.BaseView;
import org.nf.web.servlet.ServletApi;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

/**
 * @author wangliang
 * @date 2022/6/19
 * 流视图（用于文件下载）
 */
public class SteamView extends BaseView {

    private final InputStream inputStream;
    private final Map<String, String> headers;
    private int bufferSize = 2048;

    public SteamView(InputStream inputStream, Map<String, String> headers) {
        this.inputStream = inputStream;
        this.headers = headers;
    }

    public void setBufferSize(int bufferSize) {
        this.bufferSize = bufferSize;
    }

    @Override
    protected void render(ServletApi api) throws IOException {
        HttpServletResponse response = api.response();
        response.setContentType("application/octet-stream");
        headers.forEach(response::setHeader);
        try(BufferedInputStream bis = new BufferedInputStream(inputStream)) {
            OutputStream os = response.getOutputStream();
            int len = 0;
            byte[] bytes = new byte[bufferSize];
            while((len = bis.read(bytes, 0, bytes.length)) != -1){
                os.write(bytes, 0, len);
            }
        }
    }
}
